# syntax=docker/dockerfile:1.7
# 多阶段构建：构建阶段
FROM golang:1.23-bookworm AS builder

WORKDIR /app

# 复制Go模块文件
COPY go.mod go.sum ./

# 下载依赖
RUN go mod download

# 复制源代码
COPY . .

# 生成Swagger文档
RUN go install github.com/swaggo/swag/cmd/swag@latest && swag init

# 构建应用程序
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o main .

# 运行阶段：使用 Ubuntu 基础镜像以获取最新版 LibreOffice
FROM ubuntu:24.04

ENV TZ=Asia/Shanghai \
    LANG=zh_CN.UTF-8 \
    LANGUAGE=zh_CN:zh \
    LC_ALL=zh_CN.UTF-8

WORKDIR /app

# 安装最新版 LibreOffice、Python3 及中文字体、必要依赖
RUN set -eux; \
    # 替换为阿里云镜像源
    sed -i 's@archive.ubuntu.com@mirrors.aliyun.com@g' /etc/apt/sources.list.d/ubuntu.sources; \
    sed -i 's@security.ubuntu.com@mirrors.aliyun.com@g' /etc/apt/sources.list.d/ubuntu.sources; \
    apt-get update; \
    # 安装 software-properties-common 以支持 add-apt-repository
    DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
        software-properties-common \
        ca-certificates \
        curl \
        gnupg; \
    # 添加 LibreOffice PPA 获取最新版本
    add-apt-repository -y ppa:libreoffice/ppa; \
    apt-get update; \
    # 安装 LibreOffice 和其他依赖
    DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
        libreoffice \
        libreoffice-l10n-zh-cn \
        fonts-wqy-zenhei \
        fonts-wqy-microhei \
        fonts-arphic-ukai \
        fonts-arphic-uming \
        locales \
        fontconfig \
        tzdata \
        python3 \
        python3-pip \
        python3-dev \
        build-essential \
        libffi-dev \
        libssl-dev \
        libgl1 \
        libglib2.0-0 \
        libsm6 \
        libxext6 \
        libxrender1 \
        libgomp1; \
    echo 'zh_CN.UTF-8 UTF-8' > /etc/locale.gen; \
    locale-gen; \
    # 清理
    apt-get purge -y --auto-remove software-properties-common gnupg; \
    rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

# 安装 Python 依赖 (pdf2docx)
COPY requirements.txt .
RUN pip3 install --no-cache-dir --break-system-packages -r requirements.txt && \
    python3 -c "from pdf2docx import Converter; print('pdf2docx installed successfully')"

# 从构建阶段复制编译好的二进制文件
COPY --from=builder /app/main .

# 复制 Python 转换脚本
COPY scripts ./scripts

# 创建运行期需要的可写目录
RUN mkdir -p /app/uploads /app/out /app/static/images && \
    chmod +x /app/scripts/*.py

EXPOSE 18420

# 健康检查
HEALTHCHECK --interval=30s --timeout=5s --retries=3 CMD curl -f http://localhost:18420/swagger/index.html || exit 1

# 启动命令
CMD ["./main"]
